<?php
/**
 * 二维码
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-04-22
 * Time: 下午 9:50
 */
namespace Pub\wx;
class Qrcode
{
    private $Api = null;  //微信api

    private $_keyword = '';  //二维码绑定关键词
    private $_qrcode = array();  //生成的二维码数据
    private $_scene_id = 0;

    /**
     * Qrcode constructor.
     * @param $_keyword  //二维码绑定关键词
     */
    public function __construct($_keyword = '')
    {
        $this->Api = \WeAccount::create();
        $this->_keyword = $_keyword;
    }

    /**
     * 新增二维码数据
     */
    public function create()
    {
        global $_W;
        $this->qrcode();
        $_result = pdo_insert('qrcode',array(
            'uniacid'=>$_W['account']['uniacid'],
            'acid'=>$_W['acid'],
            'qrcid'=>$this->_qrcode['scene_id'],
            'name'=>$this->_keyword,
            'keyword'=>$this->_keyword,
            'model'=>1,
            'ticket'=>$this->_qrcode['ticket'],
            'expire'=>$this->_qrcode['expire_seconds'],
            'subnum'=>0,
            'createtime'=>TIMESTAMP,
            'status'=>1,
            'url'=>$this->_qrcode['url']
        ));
        if($_result) return $this->_qrcode;
        return false;
    }

    /**
     * 修改二维码数据
     * @param $_scene_id
     * @return array|bool
     */
    public function update($_scene_id)
    {
        $this->_scene_id = $_scene_id;
        $this->qrcode();
        $_result = pdo_update('qrcode',array(
            'ticket'=>$this->_qrcode['ticket'],
            'createtime'=>TIMESTAMP,
            'url'=>$this->_qrcode['url']
        ),array('qrcid'=>$_scene_id));
        if($_result) return $this->_qrcode;
        return false;
    }

    /**
     * 创建微信二维码数据
     */
    private function qrcode()
    {
        if(!$this->_scene_id) $this->_scene_id = $this->sceneId();
        $this->_qrcode = $this->Api->barCodeCreateDisposable(array(
            'action_name'=>'QR_SCENE',
            'action_info'=>array(
                'scene'=>array(
                    'scene_id'=>$this->_scene_id
                )
            )
        ));
        $this->_qrcode['scene_id'] = $this->_scene_id;
    }


    /**
     * 返回一个二维码scene_id
     * @param int $_scene_id
     * @return int
     */
    private function sceneId($_scene_id = 0){
        if(!$_scene_id) $_scene_id = TIMESTAMP;
        $_qrcode = pdo_get('qrcode',array('qrcid'=>$_scene_id),array('qrcid'));
        //如果存在在原有的值上加1
        if($_qrcode) self::isTwoScene($_scene_id+1);
        return $_scene_id;
    }
}